<template>
  <div>
    <headerX title="注册"></headerX>
    <van-form @submit="onSubmit">
      <van-field
        v-model="register.username"
        name="username"
        label="用户名"
        placeholder="用户名"
        :rules="[
          { required: false, pattern: $reg.account, message: '请填写用户名' },
        ]"
      />
      <van-field
        v-model="register.phone"
        name="phone"
        label="手机号"
        placeholder="手机号"
        :rules="[
          { required: false, pattern: $reg.phone, message: '请填写正确手机号' },
        ]"
      />
      <van-field
        v-model="register.password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="[{ required: false, pattern: $reg.pwd, message: '请填写密码' }]"
      />
      <van-field
        v-model="register.rpwd"
        type="password"
        name="rpwd"
        label="确认密码"
        placeholder="确认密码"
        :rules="[
          { required: false, validator: rpwdrule, message: '两次密码不一致' },
        ]"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>
<script>
import { Toast } from "vant";
import axios from "axios";
export default {
  data() {
    return {
      register: {},
    };
  },
  mounted() {

  },
  methods: {
    onSubmit(val) {

      axios({
        method: "get",
        url: `http://localhost:3200/user?phone=${this.register.phone}`,
      }).then((res) => {
     
        if (res.data[0]) {
          Toast("该用户已被注册");
        } else {
          axios({
            method: "post",
            url: `http://localhost:3200/user`,
            data: val,
          }).then(res=>{
          this.$router.push({name:'login',query:{phone:val.phone}})
          })
        }
      });
    },
    rpwdrule(val) {
      return this.register.password == val;
    },
  },
};
</script>